//
//  BLMyController.m
//  Byelone
//
//  Created by 乔小乔 on 2020/12/14.
//

#import "BLMyController.h"
#import "BLMy_Cell_Index.h"
#import "BLMy_Cell_IndexCommon.h"
#import "BLMy_SignView.h"

#import "BLLoginController.h"
#import "BLSafeSetController.h"
#import "BLMeet_DetailController.h"

#import "BLInfoInputController.h"
#import "BLSetController.h"
#import "BLMyMeetController.h"
#import "BLCertificateController.h"
#import "BLInfoPhotosViewController.h"
#import "BLInfoTestController.h"
#import "BLInfoTestResultVC.h"
#import "BLInfoAvatarController.h"
#import "BLMyOrderController.h"
#import "BLInfoPhotoWallController.h"
#import "BLInfoAboutUsController.h"

static NSString *reuse_BLMy_Cell_Index = @"Reuse_BLMy_Cell_Index";
static NSString *reuse_BLMy_Cell_IndexCommon = @"Reuse_BLMy_Cell_IndexCommon";
@interface BLMyController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableViewList;
@property (nonatomic, strong) NSArray *arrayData;
@property (nonatomic, strong) BLInfoUserInfo *infoModel;
@property (nonatomic, strong) BLInfoBaseInfo *baseModel;
@property (nonatomic, strong) UIView *viewFooter;
@end

@implementation BLMyController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"我的";
    self.arrayData = @[@{@"title":@"资料",@"img":@""},@{@"title":@"我的照片墙",@"img":@"my_icon_photo"},@{@"title":@"我的认证",@"img":@"my_icon_rz"},@{@"title":@"我的性格",@"img":@"my_icon_trait"},@{@"title":@"我的期望",@"img":@"my_icon_hope"},@{@"title":@"我的约会",@"img":@"my_icon_meet"},@{@"title":@"关于我们",@"img":@"my_icon_about"}];
    [self.tableViewList reloadData];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData) name:Notification_login object:nil];
    if ([BLUserManager shareUser].userInfo) {
        self.infoModel = [BLUserManager shareUser].userInfo;
    }else{
        [self loadData];
    }
}

- (void)loadData{
    //个人中心
    if ([BLUserManager shareUser].userPpu) {
        [BLHttpTool getHttpRequest:BL_USER_CENTER param:BL_EMPTYDIC finish:^(NSURLSessionDataTask * _Nonnull data, NSDictionary * _Nonnull obj) {
            [self.tableViewList.mj_header endRefreshing];
            BLInfoUserInfo *model = [BLInfoUserInfo mj_objectWithKeyValues:obj[@"content"]];
            [BLUserManager shareUser].userInfo = model;
            self.infoModel = model;
            
            //获取个人基本信息
            [BLHttpTool getHttpRequest:BL_USER_BASEINFO param:BL_EMPTYDIC finish:^(NSURLSessionDataTask * _Nonnull data, NSDictionary * _Nonnull obj) {
                BLInfoBaseInfo *baseInfo = [BLInfoBaseInfo mj_objectWithKeyValues:obj[@"content"]];
                [BLUserManager shareUser].baseInfo = baseInfo;
                self.baseModel = baseInfo;
                [BLHttpTool getHttpRequest:BL_USER_ETAIL param:@{} finish:^(NSURLSessionDataTask * _Nonnull data, NSDictionary * _Nonnull obj) {
                    BLInfoDetailInfo *detailInfo = [BLInfoDetailInfo mj_objectWithKeyValues:obj[@"content"]];
                    [BLUserManager shareUser].detailInfo = detailInfo;
                    [self.tableViewList reloadData];
                } failedBlock:^(id  _Nonnull data, NSError * _Nonnull error) {
                    
                }];
                
            } failedBlock:^(id  _Nonnull data, NSError * _Nonnull error) {
                
            }];
        } failedBlock:^(id  _Nonnull data, NSError * _Nonnull error) {
            [self.tableViewList.mj_header endRefreshing];
        }];
    }
}
#pragma mark - method
- (void)clickSet{
    BLSetController *vc = [[BLSetController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)clickEdit{
    BLMeet_DetailController *vc = [[BLMeet_DetailController alloc]init];
    vc.isShouldEdit = YES;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)clickHeadPic{
    BLInfoAvatarController *vc = [[BLInfoAvatarController alloc]init];
    vc.isEdit = YES;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)clickOrder:(UIButton *)sender{
    NSInteger index = sender.tag;
     BLMyOrderController *vc = [[BLMyOrderController alloc]init];
    if (index==101) {
        vc.selectIndex = 0;
    }else if(index==102){
        vc.selectIndex = 1;
    }   
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)clickSign:(UIButton *)sender{
    //签到
    [BLHttpTool getHttpRequest:BL_USER_SIGN_LIST param:BL_EMPTYDIC finish:^(NSURLSessionDataTask * _Nonnull data, NSDictionary * _Nonnull obj) {
       
       
        [self showSignView:[obj objectForKey:@"content"]];
        NSLog(@"%@",obj);
        
    } failedBlock:^(id  _Nonnull data, NSError * _Nonnull error) {
        
    }];
}

-(void)showSignView:(NSDictionary *)dic{
    [BLMy_SignView showSignViewWithDic:dic click:^{
        
        [BLHttpTool getHttpRequest:BL_USER_SIGN param:BL_EMPTYDIC finish:^(NSURLSessionDataTask * _Nonnull data, NSDictionary * _Nonnull obj) {
            
            if ([[obj objectForKey:@"code"] integerValue] == 1) {
                
            }else{
                
            }
            
            NSLog(@"%@",obj);
        } failedBlock:^(id  _Nonnull data, NSError * _Nonnull error) {
            
        }];
        
    }];
    
}


- (void)clickLogout{
    [BLUserManager shareUser].userInfo = nil;
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    [prefs removeObjectForKey:K_Login_Ppu];
    [prefs removeObjectForKey:K_Login_RegisterStep];
    [prefs removeObjectForKey:K_Login_Phone];
    [prefs synchronize];
    [[NSNotificationCenter defaultCenter] postNotificationName:Notification_login object:nil];
//    [[BLHUD shareHud] showtip:@"退出成功，请重新登录"];
    [BLTool loginWithCompletion:^{
        
    } fail:^{
        self.navigationController.tabBarController.selectedIndex = 0;
    }];
}
#pragma mark - delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.arrayData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dict = self.arrayData[indexPath.row];
    NSString *title = dict[@"title"];
    if ([title isEqualToString:@"资料"]) {
        BLMy_Cell_Index *cell = [tableView dequeueReusableCellWithIdentifier:reuse_BLMy_Cell_Index forIndexPath:indexPath];
        [cell reloadWithData:self.infoModel baseModel:self.baseModel];
        [cell.btnSet addTarget:self action:@selector(clickSet) forControlEvents:UIControlEventTouchUpInside];
        [cell.btnEdit addTarget:self action:@selector(clickEdit) forControlEvents:UIControlEventTouchUpInside];
        [cell.btnHeadPic addTarget:self action:@selector(clickHeadPic) forControlEvents:UIControlEventTouchUpInside];
        [cell.btnLeft addTarget:self action:@selector(clickOrder:) forControlEvents:UIControlEventTouchUpInside];
        [cell.btnRight addTarget:self action:@selector(clickOrder:) forControlEvents:UIControlEventTouchUpInside];
        [cell.signBtn addTarget:self action:@selector(clickSign:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }else{
        BLMy_Cell_IndexCommon *cell = [tableView dequeueReusableCellWithIdentifier:reuse_BLMy_Cell_IndexCommon forIndexPath:indexPath];
        cell.labelTitle.text = title;
        cell.imgIcon.image = [UIImage imageNamed:dict[@"img"]];
        
        CGRect frame = CGRectMake(0, 0, BL_WINDOW_WIDTH-30, 50);
        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect: frame byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(0,0)];

        cell.layoutTop.constant = 0;
        cell.layoutBottom.constant = 0;
        if (indexPath.row == 1) {
            cell.layoutTop.constant = 7;
            maskPath = [UIBezierPath bezierPathWithRoundedRect: frame byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(6,6)];
        }else if(indexPath.row == self.arrayData.count-1){
            cell.layoutBottom.constant = 20;
            maskPath = [UIBezierPath bezierPathWithRoundedRect: frame byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(6,6)];
            cell.viewLine.hidden = YES;
        }
        //创建 layer
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
        maskLayer.frame = frame;
        //赋值
        maskLayer.path = maskPath.CGPath;
        cell.viewBg.layer.mask = maskLayer;
        
        cell.labelDesc.text = @"";
        if ([title isEqualToString:@"我的照片墙"]) {
            cell.labelDesc.text = [NSString stringWithFormat:@"%@/6",self.infoModel.photoNum?:@"0"];
        }else if ([title isEqualToString:@"我的认证"]) {
            cell.labelDesc.text = [NSString stringWithFormat:@"%@/2",self.infoModel.authNum?:@"0"];
        }else if ([title isEqualToString:@"我的期望"]) {
            cell.labelDesc.text = self.infoModel.expectationTest?@"已完成":@"未完成";
        }else if ([title isEqualToString:@"我的性格"]) {
            cell.labelDesc.text = self.infoModel.personalityTest?@"已完成":@"未完成";
        }
    
        return cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row==0) {
        return 216+BL_STATUS_HEIGHT;
    }
    return 50+((indexPath.row==1)?7:0)+((indexPath.row==self.arrayData.count-1)?20:0);
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dict = self.arrayData[indexPath.row];
    NSString *title = dict[@"title"];
    if ([title isEqualToString:@"安全设置"]) {
        BLSafeSetController *vc = [[BLSafeSetController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([title isEqualToString:@"资料"]) {
        BLMeet_DetailController *vc = [[BLMeet_DetailController alloc]init];
        vc.isShouldEdit = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([title isEqualToString:@"我的照片墙"]) {
        BLInfoPhotoWallController *vc = [[BLInfoPhotoWallController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([title isEqualToString:@"我的认证"]) {
        BLCertificateController *vc = [[BLCertificateController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([title isEqualToString:@"我的性格"]) {
        [self toTest:BLInfoTestTypeTrait];
    }else if ([title isEqualToString:@"我的期望"]) {
        [self toTest:BLInfoTestTypeLover];
    }else if ([title isEqualToString:@"我的约会"]) {
        BLMyMeetController *vc = [[BLMyMeetController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if ([title isEqualToString:@"关于我们"]) {
        BLInfoAboutUsController *vc = [[BLInfoAboutUsController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)toTest:(BLInfoTestType)type{
    //    先获取性格测试结果，有结果显示结果页，没有结果显示测试页
    [BLHttpTool postWithPath:BL_TEST_RESULT params:@{@"testType":@(type)} successBlock:^(NSDictionary * _Nonnull obj) {
        BOOL isHasResult = NO;
        if ([obj[@"content"] isKindOfClass:[NSDictionary class]]) {
            BLTestResultModel *testModel = [BLTestResultModel mj_objectWithKeyValues:obj[@"content"]];
            if (testModel.testResultItemList.count>0) {
                isHasResult = YES;
                BLInfoTestResultVC *vc = [[BLInfoTestResultVC alloc]init];
                vc.arrayResult = testModel.testResultItemList;
                vc.testType = (BLTestResultType)type;
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
        if (!isHasResult) {
            BLInfoTestController *vc = [[BLInfoTestController alloc]init];
            vc.testType = type;
            [self.navigationController pushViewController:vc animated:YES];
        }
    } failedBlock:^(NSURLSessionDataTask * _Nonnull data, NSError * _Nonnull error) {
        
    }];
}
#pragma mark - set&get
- (UITableView *)tableViewList{
    if (!_tableViewList) {
        _tableViewList = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, BL_WINDOW_WIDTH, BL_WINDOW_HEIGHT-BL_TABBAR_HEIGHT)];
        [self.view addSubview:_tableViewList];
        _tableViewList.backgroundColor = [UIColor clearColor];
        _tableViewList.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableViewList.delegate = self;
        _tableViewList.dataSource = self;
        if (@available(iOS 11.0, *)) {
            _tableViewList.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }else{
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        [_tableViewList registerNib:[UINib nibWithNibName:@"BLMy_Cell_Index" bundle:nil] forCellReuseIdentifier:reuse_BLMy_Cell_Index];
        [_tableViewList registerNib:[UINib nibWithNibName:@"BLMy_Cell_IndexCommon" bundle:nil] forCellReuseIdentifier:reuse_BLMy_Cell_IndexCommon];
        _tableViewList.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
        
        _tableViewList.tableFooterView = self.viewFooter;
    }
    return _tableViewList;
}
- (UIView *)viewFooter{
    if (!_viewFooter) {
        _viewFooter = [[UIView alloc]initWithFrame:CGRectMake(0, 0, BL_WINDOW_WIDTH, 100)];
        _viewFooter.backgroundColor = [UIColor clearColor];
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(28, 50, BL_WINDOW_WIDTH-56, 44);
        [button setTitle:@"退出登录" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:16];
        [button setGradientBackgroundWithColors:@[[UIColor chColorWithHexString:@"#8881FD"],[UIColor chColorWithHexString:@"#6B71F5"]] locations:@[@(0.0f), @(1.0f)]  startPoint:CGPointMake(0, 0) endPoint:CGPointMake(1, 0)];
        button.layer.cornerRadius = 22;
        button.layer.masksToBounds = YES;
        [_viewFooter addSubview:button];
        
        [button addTarget:self action:@selector(clickLogout) forControlEvents:UIControlEventTouchUpInside];
    }
    return _viewFooter;
}
@end
